package com.xlongwei.accounts.dao;

import java.util.Collections;
import java.util.List;

import org.noear.solon.annotation.Component;
import org.noear.solon.annotation.Inject;
import org.noear.solon.data.annotation.Cache;
import org.noear.solon.data.annotation.CacheRemove;
import org.noear.solon.data.annotation.Tran;
import com.xlongwei.accounts.config.MySqlUtils;
import com.xlongwei.accounts.model.Ledger;

@Component
public class LedgerDao {
    @Inject
    MySqlUtils sqlUtils;

    @Tran
    @CacheRemove(keys = "ledger.${},ledgers.${row.userid}")
    public Integer create(Ledger row) {
        assert row.getLedgerid() == null;
        Object key = sqlUtils.sql("insert into t_ledger(type,name,userid) values(?,?,?)", row.getType(),
                row.getName(), row.getUserid()).updateReturnKey();
        return Integer.parseInt(key.toString());
    }

    @Cache(key = "ledger.${ledgerid}")
    public Ledger retrieve(Integer ledgerid) {
        return sqlUtils.sql("select ledgerid,type,name,userid from t_ledger where ledgerid=?", ledgerid)
                .queryRow(Ledger.class);
    }

    @Tran
    @CacheRemove(keys = "ledger.${row.ledgerid},ledgers.${row.userid}")
    public Integer update(Ledger row) {
        assert row.getLedgerid() != null;
        return sqlUtils.sql("update t_ledger set name=? where ledgerid=?", row.getName(),
                row.getLedgerid()).update();
    }

    @Cache(key = "ledgers.${userid}")
    public List<Ledger> list(Integer userid) {
        List<Ledger> list = sqlUtils.sql("select ledgerid,type,name,userid from t_ledger where userid=0 or userid=? order by ledgerid", userid)
                .queryRowList(Ledger.class);
        return list != null ? list : Collections.emptyList();
    }
}
